using UnityEngine;
using System.Collections;

/// <summary>
/// There are three view mode in game.
/// </summary>
public enum PlayerViewMode
{
	Forward,
	Backward,
	Horizontal,
}

/// <summary>
/// Control movement of player's camera.
/// </summary>
public class PlayerCameraController : MonoBehaviour
{
	/// <summary>
	/// height of camera relative to view anchor
	/// </summary>
	public float height = 5.0f;
	
	/// <summary>
	/// The distance between camera and view anchor, 
	/// along forward direction.
	/// </summary>
	public float distance = 10.0f;
	
	/// <summary>
	/// camera will always look at lookDistance beyond view anchor.
	/// </summary>
	public float lookDistance = 10.0f;
	
	/// <summary>
	/// Changes camera's view mode.
	/// </summary>
	public void changeViewMode (PlayerViewMode viewMode)
	{
		m_viewMode = viewMode;
	}
	
	void Awake ()
	{
		if (Camera.main != null)
		{
			m_cameraTransform = Camera.main.transform;
		}
		
		if (m_cameraTransform == null)
		{
			Debug.LogError ("MainCamera not found!");
			return;
		}
		
		m_playerController = gameObject.GetComponent<PlayerController> ();
		m_viewMode = PlayerViewMode.Forward;
	}
	
	void LateUpdate ()
	{
		Vector3 viewAnchor = m_playerController.GetViewAnchor ();
		
		Vector3 toCameraDirection = m_playerController.GetViewForwardXZ ();
		if (m_viewMode == PlayerViewMode.Forward)
		{
			toCameraDirection.Set (-toCameraDirection.x, 0, -toCameraDirection.z);
		}
		else if (m_viewMode == PlayerViewMode.Horizontal)
		{
			toCameraDirection.Set (toCameraDirection.z, 0, -toCameraDirection.x);
		}
		
		toCameraDirection = toCameraDirection * distance;
		toCameraDirection.y = height;
		m_cameraTransform.position = viewAnchor + toCameraDirection;
		toCameraDirection.y = 0;
		m_cameraTransform.LookAt (viewAnchor - toCameraDirection * lookDistance / distance);
	}
	
	/// <summary>
	/// player controller.
	/// </summary>
	PlayerController m_playerController;
	
	/// <summary>
	/// Transform of main camera.
	/// </summary>
	Transform m_cameraTransform = null;
	
	/// <summary>
	/// current view mode.
	/// </summary>
	PlayerViewMode m_viewMode;
}